package com.youhui.weixin.weixin.service;

import com.youhui.weixin.common.MythConfig;
import com.youhui.weixin.dao.GoodsDao;
import com.youhui.weixin.domain.Goods;
import com.youhui.weixin.utils.weixin.WXMessagesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * Created by https://github.com/kuangcp on 17-11-4  下午8:42
 *
 * @author kuangcp
 */
@Service
public class MessageService {
    @Autowired
    GoodsDao goodsDao;

    /**
     * 分享出来的字符串进行搜索
     */
    public String search(String content){
        content = content.split("】")[0].split("【")[1];
        if(content.split("\\）").length>1) {
            content = content.split("\\）")[0].split("\\（")[1];
        }
        Goods good = goodsDao.findOneByName(content);
        if ( good!=null ){
            return "http://wx.jjyouhuigo.com/good/"+good.getGoodsId();
        }else{
            return "0";
        }
    }

    public Page<Goods> searchSimple(String name){
        Pageable pageable = new PageRequest(0, MythConfig.SEARCH_SIZE);
        Page<Goods> goodsList = goodsDao.findListByName(name, pageable);
        if(goodsList==null||goodsList.getSize()==0){
            return null;
        }
        return goodsList;
//        if(goodsList==null||goodsList.getSize()==0){
//            return "0";
//        }else{

//            StringBuilder temp = new StringBuilder("搜索到商品：\n");
//            for(Goods good : goodsList){
//                temp.append("<a href=\"http://wx.jjyouhuigo.com/good/").append(good.getGoodsId()).append("\">")
//                        .append(good.getName()).append("</a>\n\n");
//            }
//            temp.append("<a href=\"wx.jjyouhuigo.com/searchs\">点击搜索更多</a>");
//            return temp.toString();
//        }
    }

    /**
     * 微信特殊的校验方式
     */
    public boolean sort(String signature, String timestamp, String nonce){
        // 排序
        String [] arrs = new String[]{MythConfig.CONNECTION_TOKEN, timestamp, nonce};
        Arrays.sort(arrs);
        // 生成随机字符串
        StringBuilder temp = new StringBuilder();
        for (String arr : arrs) {
            temp.append(arr);
        }
        // sha加密
        String result = WXMessagesUtils.getSha1(temp.toString());
        return result.equals(signature);
    }


}
